<?php

namespace App\Services;

use App\Services\EasyWeChatServices;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Log;


class LoginServices
{
    function __construct(User $userModel) {
        $this->userModel = $userModel;
    }

    //账号密码登录
    public function account_login($account){
        $account_user = $this->userModel->where('nickname',$account)->first();

        $token = JWTAuth::fromUser($account_user);
        $account_user->token = $token;

        return $account_user;
    }

    public function wx_login($wx_code){
        //Log::info('wx_login进来了'.$wx_code);
            $app = EasyWeChatServices::app();

            $wx_user = $user = $app->oauth->userFromCode($wx_code);

            $openid = $wx_user->getId();
            //dd($wx_user,$openid);
            // 说明没有获取到openid
            if(empty($openid)){
                throw new \Exception('获取openid失败,请检查授权code');
            }

            // 查找會員是否存在
            $userModel = new User();
            $userObj = $userModel
                ->where('wx_openid','=',$openid)
                -> first();

            if(empty($userObj)){
                //头像上传
                $avatar = $wx_user->getAvatar();
                // 定义保存的路径
                $avatarUrl = 'avatar/' . date('Ymd');

                // 验证文件夹是否存在
                if(!is_dir('upload/' . $avatarUrl)){
                    // 不存在则创建
                    mkdir('upload/' . $avatarUrl,0777,true);
                }

                // 获取图片信息
                $param = @getimagesize($avatar);
                // 获取文件后缀名
                $suffix = explode('/',$param['mime'])[1];
                // 获取图片名称
                $imagesName = md5(time()). '.' . $suffix;

                $avatarUrl = 'upload/'. $imagesName;
                // 下载图片
                downloadImages($avatar,$avatarUrl);

                $userModel->nickname = $wx_user->getName();
                $userModel->head_img = $avatarUrl;
                $userModel->wx_openid = $openid;

                $result = $userModel->save();
                if(!$result){
                    throw new \Exception('授权异常,请重新授权');
                }

                $userObj = $userModel;
            }

            // 自動登錄
            $token = JWTAuth::fromUser($userObj);
            $userObj->token = $token;
            return $userObj;

    }
}